//
//  ViewController.m
//  Printer
//
//  Created by Bcc on 5/15/16.
//  Copyright © 2016 eReach. All rights reserved.
//

#import "ViewController.h"
#import "UELabel.h"
#import "MBProgressHUD+MJ.h"
#import "ConfirmViewController.h"
@interface ViewController ()
{
    UELabel *codeF;
}
@end

@implementation ViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    codeF.text = @"";
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = Blue_Color;
    [self createSubViews];
//    [self getImageFromSever1];
    NSLog(@"方向：%ld",(long)self.interfaceOrientation);
    
}

- (void)createSubViews
{
    
    
    UILabel *hintL = [[UILabel alloc] init];
    hintL.frame = CGRectMake(51, 515, 100, 40);
    hintL.backgroundColor = [UIColor clearColor];
    hintL.textColor = [UIColor whiteColor];
    hintL.text = @"输入验证码";
    hintL.font = DEFAULT_FONT_20;
    [self.view addSubview:hintL];
    
    
    codeF = [[UELabel alloc] init];
    codeF.insets = UIEdgeInsetsMake(0, 5, 0, 0);
    codeF.frame = CGRectMake(hintL.left,hintL.bottom, 218, 40);
    codeF.backgroundColor  = Line_Gray_Color;
    codeF.layer.cornerRadius = 5;
//    codeF.text = @"61985";
    codeF.layer.masksToBounds = YES;
    [self.view addSubview:codeF];
    
    
    CGFloat bigBtnW = 76;
    CGFloat bigBtnMargin = 36;
    CGFloat bigBtnTopMargin = 43;
    UEButton *confirm = [[UEButton alloc] initWithFrame:CGRectMake(codeF.center.x - bigBtnW - bigBtnMargin/2 , codeF.bottom + bigBtnTopMargin, bigBtnW, bigBtnW)];
    [confirm setTitle:@"确定" forState:UIControlStateNormal];
    [confirm addTarget:self action:@selector(confirm:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:confirm];
    
    UEButton *cancel = [[UEButton alloc] initWithFrame:CGRectMake(codeF.center.x  + bigBtnMargin/2 , codeF.bottom + bigBtnTopMargin, bigBtnW, bigBtnW)];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel addTarget:self action:@selector(cancel:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancel];
    
    CGFloat smallBtnX = 316;
    CGFloat smallBtnW = 56;
    CGFloat smallMargin = 15;
    CGFloat smallMarginY = 10;
    CGFloat smallBtnY = 470 - smallBtnW - smallMargin;
    for (int i = 0; i < 12; i++) {
        if (i%3 == 0) {
            smallBtnX = 316;
            smallBtnY = smallBtnY + smallBtnW + smallMarginY;
        }

        UEButton *numBtn = [[UEButton alloc] initWithFrame:CGRectMake(smallBtnX,smallBtnY,smallBtnW,smallBtnW)];
        numBtn.tag = i;
        if (i == 9) {
            [numBtn setTitle:@"" forState:UIControlStateNormal];
        }else if (i == 10){
            [numBtn setTitle:@"0" forState:UIControlStateNormal];
        }else if (i == 11){
            [numBtn setTitle:@"" forState:UIControlStateNormal];
            [numBtn setImage:[UIImage imageNamed:@"deleteNum_icon"] forState:UIControlStateNormal];
        }else{
            [numBtn setTitle:[NSString stringWithFormat:@"%d",i + 1] forState:UIControlStateNormal];
        }
        [numBtn addTarget:self action:@selector(numBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:numBtn];
        
        smallBtnX = smallBtnX + smallMargin + smallBtnW;

        
    }


}


- (void)confirm:(UIButton *)sender
{
    if (codeF.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请输入验证码" message:nil delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [self getImageFromSever];
}


- (void)cancel:(UIButton *)sender
{
    codeF.text = @"";
}


- (void)numBtnClick:(UIButton *)sender
{
    
    if (sender.tag == 11) {
        if (codeF.text.length > 0) {
            codeF.text = [codeF.text substringToIndex:[codeF.text length] - 1];
        }
    }else if (sender.tag == 9){
        
    }else{
        if (codeF.text.length < 6) {
            codeF.text = [NSString stringWithFormat:@"%@%@",codeF.text?codeF.text:@"",sender.titleLabel.text];
        }
        
    }
}




- (void)getImageFromSever
{
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    // 1.创建一个网络路径
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://yz.eintsoft.com:8081/sw/rlPrint/showImageByCode.action?extraCode=%@",codeF.text]];
    
    
    // 2.创建一个网络请求
    
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    
    // 3.获得会话对象
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    // 4.根据会话对象，创建一个Task任务：
    
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSLog(@"从服务器获取到数据");        /*          对从服务器获取到的数据data进行相应的处理：        */
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
        NSLog(@"%@",[dict[@"errinfo"] class]);
        if ([dict[@"result"] intValue] == 1 && dict[@"errinfo"] ) {
            [self getImageFromSeverWithUrl:dict[@"errinfo"]];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showError:@"未找到图片" toView:self.view];
            });
        }
    }];
    
    [sessionDataTask resume];
    
}


- (void)getImageFromSeverWithUrl:(NSString *)urlStr
{
    // 1.创建一个网络路径
    NSURL *url = [NSURL URLWithString:urlStr];
    
    
    // 2.创建一个网络请求
    
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    
    // 3.获得会话对象
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    // 4.根据会话对象，创建一个Task任务：
    
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSLog(@"从服务器获取到数据");        /*          对从服务器获取到的数据data进行相应的处理：        */
        //        NSLog(@"0000000%@",data);
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view];
            UIImage *img = [[UIImage alloc] initWithData:data];
            ConfirmViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ConfirmViewController"];
            vc.image = img;
            [self presentViewController:vc animated:YES completion:^{
                
            }];
        });
        
        
    }];
    
    [sessionDataTask resume];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

@end
